package com.fzshang.commen.util.aliOSS;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectRequest;
import com.fzshang.commen.entity.Constant;

import java.io.InputStream;
import java.util.UUID;

/**
 * This sample demonstrates how to upload/download an object to/from
 * Aliyun OSS using the OSS SDK for Java.
 */
public class OSS_File {
    private static ClientConfiguration conf;

    static {
        conf = new ClientConfiguration();
// 设置OSSClient允许打开的最大HTTP连接数，默认为1024个。
        conf.setMaxConnections(Constant.OSS_MaxConnections);
// 设置Socket层传输数据的超时时间，默认为50000毫秒。
        conf.setSocketTimeout(Constant.OSS_SocketTimeout);
// 设置建立连接的超时时间，默认为50000毫秒。
        conf.setConnectionTimeout(Constant.OSS_ConnectionTimeout);
// 设置从连接池中获取连接的超时时间（单位：毫秒），默认不超时。
        conf.setConnectionRequestTimeout(Constant.OSS_ConnectionRequestTimeout);
// 设置连接空闲超时时间。超时则关闭连接，默认为60000毫秒。
        conf.setIdleConnectionTime(Constant.OSS_IdleConnectionTime);
// 设置失败请求重试次数，默认为3次。
        conf.setMaxErrorRetry(Constant.OSS_MaxErrorRetry);
    }

    //上传图片 返回图片url
    public static String uploadImage(String fileName, InputStream inputStream) {
        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(Constant.OSS_endpoint, Constant.OSS_accessKeyId, Constant.OSS_accessKeySecret, conf);
        try {
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String[] names = fileName.split("[.]");
            String name = uuid + "." + names[names.length - 1];
            ossClient.putObject(new PutObjectRequest(Constant.OSS_bucketName_user, Constant.OSS_FILE_PATH + name, inputStream));
            return Constant.OSS_KEY + Constant.OSS_FILE_PATH + name + Constant.OSS_LAST;
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println(e.getMessage());
        } finally {
            ossClient.shutdown();
        }
        return null;

    }
    /**
     * 删除某个文件
     *
     */
    public void delFile(  String url) {
        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(Constant.OSS_endpoint, Constant.OSS_accessKeyId, Constant.OSS_accessKeySecret, conf);
        String[] key = url.split( Constant.OSS_FILE_PATH + "");
        String[] urls = key[1].split("\\?");
        String newUrl =  Constant.OSS_FILE_PATH +urls[0];
        ossClient.deleteObject(Constant.OSS_bucketName_user,  newUrl);
        ossClient.shutdown();
    }
    public static void main(String[] args) {
        OSS_File.uploadImage("", null);
    }
}